const express = require('express');
const router = express.Router();
const MsgJsonHelper = require('../common/MsgJsonHelper');
var svgCaptcha = require('svg-captcha');
const jsmd5 = require('js-md5');
var AuthorizeLogin = require('../common/AuthorizeLogin');
const ZK_LIULIANG = require('../model/ZK_LIULIANG');
const {
	DataAccess,
	OperationEnum,
	Public,
} = require('msg-dataaccess-base');
const ds = new DataAccess();

router.post('/login', (req, res) => {
	AuthorizeLogin.Login(req, res);
});

router.post('/logout', (req, res) => {
	Logout(req, res);
});

router.get('/verify', (req, res) => {
	Verifylogin(req, res);
});

router.get('/captcha', (req, res) => {
	Createcaptcha(req, res);
});

router.get('/access', (req, res) => {
	WebAccess(req, res);
});

/**
 * 检查是否在线
 * @param {*} res
 */
function Verifylogin(req, res) {
	let user = req.UserInfo;
	if (user) {
		user['ZK_PASSWORD'] = user['ZK_PASSWORD'].replace(/^(.{5})(.+)(.{5})$/, '$1*****$3');
	}
	res.json(MsgJsonHelper.DefaultJson(user, user === undefined ? false : true, ''));
}

/**
 * 退出登录
 * @param {*} req
 * @param {*} res
 */
function Logout(req, res) {
	res.json(MsgJsonHelper.DefaultJson('', true, '请清空登录票据'));
}

/**
 * 生成图片二维码
 * @param {*} req
 * @param {*} res
 * @verify jsmd5(jsmd5.digest(captcha))
 */
function Createcaptcha(req, res) {
	let captcha = svgCaptcha.create({
		size: 4,
		noise: 2,
		color: true,
		width: 150,
		height: 50,
		background: 'transparent',
	});
	res.json(MsgJsonHelper.DefaultJson(captcha.data, true, jsmd5(jsmd5.digest(captcha.text.toLowerCase()))));
}

/**
 * 用户访问时触发
 * @param {*} req 
 * @param {*} res 
 */
function WebAccess(req, res) {
	let ip = req.headers['x-forwarded-for'] ||
		req.connection.remoteAddress ||
		req.socket.remoteAddress ||
		req.connection.socket.remoteAddress ||
		'';
	let userAgent = req.headers['user-agent'] || '';
	let record = new ZK_LIULIANG();
	record.ZK_ID = Public.BuildCode();
	record.ZK_IP = ip;
	record.ZK_AGENT = userAgent;
	record.ZK_TIME = new Date();
	record.EB_ISDELETE = '0';
	ds.TransRunQuery(Public.OperationSQLParams(record, OperationEnum.Create)).then(flag => {
		res.json(MsgJsonHelper.DefaultJson('', flag, flag ? '保存成功' : '访问流量保存异常'));
	}).catch(() => {
		res.json(MsgJsonHelper.DebugJson('WebAccess接口请求异常'));
	});
}

module.exports = router;
